package org.budo.netty.servlet.util;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

/**
 * @author lmw
 */
public class TimeUtil {
    private static final TimeZone _GMT = TimeZone.getTimeZone("GMT");

    private final static GregorianCalendar _CALENDAR = new GregorianCalendar(_GMT);

    private static final String[] DAYS = { "Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

    private static final String[] MONTHS = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Jan" };

    public static String dateHeader(long date) {
        StringBuilder stringBuilder = new StringBuilder(32);
        stringBuilder.setLength(0);

        _CALENDAR.setTimeInMillis(date);

        int day_of_week = _CALENDAR.get(Calendar.DAY_OF_WEEK);
        int day_of_month = _CALENDAR.get(Calendar.DAY_OF_MONTH);
        int month = _CALENDAR.get(Calendar.MONTH);
        int year = _CALENDAR.get(Calendar.YEAR);
        int century = year / 100;
        year = year % 100;

        int hours = _CALENDAR.get(Calendar.HOUR_OF_DAY);
        int minutes = _CALENDAR.get(Calendar.MINUTE);
        int seconds = _CALENDAR.get(Calendar.SECOND);

        stringBuilder.append(DAYS[day_of_week]);
        stringBuilder.append(',');
        stringBuilder.append(' ');

        append2digits(stringBuilder, day_of_month);

        stringBuilder.append(' ');
        stringBuilder.append(MONTHS[month]);
        stringBuilder.append(' ');

        append2digits(stringBuilder, century);
        append2digits(stringBuilder, year);

        stringBuilder.append(' ');
        append2digits(stringBuilder, hours);

        stringBuilder.append(':');
        append2digits(stringBuilder, minutes);

        stringBuilder.append(':');
        append2digits(stringBuilder, seconds);

        stringBuilder.append(" GMT");
        return stringBuilder.toString();
    }

    public static void append2digits(StringBuilder stringBuilder, int value) {
        if (value < 100) {
            stringBuilder.append((char) (value / 10 + '0'));
            stringBuilder.append((char) (value % 10 + '0'));
        }
    }
}